<template>
    <div class="order-list">
        <van-button type="danger" size="large" @click="onClickClearOrders" class="clear-button">清空订单</van-button>
        <div class="card-item" v-for="(order, index) in orderList" :key="order.id" @mouseenter="handleMouseEnter(index)"
            @mouseleave="handleMouseLeave(index)" :class="{ 'card-item-hover': isHovering[index] }">
            <van-cell class="card-header" :title="`订单号：${order.id}`" :label="`订单时间：${formatTime(order.createTime)}`">
                <template #default>
                    <span>{{ orderStatus(order) }}</span>
                    <span v-if="order.status!== -1" @click="onClickOrderCancel(order.id)"> | 取消订单</span>
                </template>
            </van-cell>
            <van-row v-for="item in order.products" :key="item.id" @click="onClick2OrderDetail(order.id)"
                class="product-row">
                <van-col span="4">
                    <van-image :src="item.pic" width="60" height="60" :error-src="errorImage" fit="cover" />
                </van-col>
                <van-col span="20">
                    <van-cell :title="item.title" :label="item.spec"
                        class="van-ellipsis product-cell"></van-cell>
                    <van-row style="padding-left: 20px;text-align: right;" type="flex" justify="space-between"
                        class="price-row">
                        <van-col span="5">{{ formatPrice(item.price) }}</van-col>
                        <van-col span="4">X</van-col>
                        <van-col span="5">{{ item.count }}</van-col>
                        <van-col span="3">=</van-col>
                        <van-col span="7">{{ formatPrice(item.price * item.count) }}</van-col>
                    </van-row>
                </van-col>
            </van-row>
            <div class="amount">
                实付金额：
                <span style="color:red">{{ formatPrice(order.amount) }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import { showConfirmDialog, showToast } from 'vant';
import { deleteOrderByIdAPI } from "@/api/order.js";

export default {
    data() {
        return {
            orderList: [],
            isHovering: [],
            errorImage: 'https://picsum.photos/300/300?text=图片加载失败'
        };
    },
    created() {
        this.getOrderListFromLocalStorage();
        
        // 仅为没有状态的订单设置默认状态，不覆盖已有状态
        this.orderList.forEach(order => {
            if (order.status === undefined) {
                order.status = 0; // 明确设置默认状态为未支付
            }
        });
        
        this.saveOrderListToLocalStorage();
    },
    methods: {
        getOrderListFromLocalStorage() {
            try {
                const orderHistory = JSON.parse(localStorage.getItem('orderHistory')) || [];
                this.orderList = orderHistory.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
                this.isHovering = new Array(this.orderList.length).fill(false);
            } catch (error) {
                console.error('获取本地订单列表失败:', error);
                this.orderList = [];
            }
        },
        onClick2OrderDetail(id) {
            // 跳转到订单详情页
            this.$router.push({
                name: "orderDetail",
                params: { id }
            });
        },
        onClickClearOrders() {
            showConfirmDialog({
                message: '您确定要清空所有订单吗?'
            }).then(() => {
                try {
                    localStorage.removeItem('orderHistory');
                    this.getOrderListFromLocalStorage();
                    showToast("订单已全部清空");
                } catch (error) {
                    console.error('清空订单失败:', error);
                    showToast("清空订单失败");
                }
            });
        },
        formatPrice(price) {
            return `¥${price.toFixed(2)}`;
        },
        formatTime(timeStr) {
            const date = new Date(timeStr);
            return date.toLocaleString();
        },
        // 移除 default 分支，只保留已知状态
        orderStatus(order) {
            switch (order.status) {
                case 0: return '未支付';
                case 1: return '已支付';
                case -1: return '已取消';
            }
        },
        onClickOrderCancel(id) {
            showConfirmDialog({
                message: '您确定要取消该订单吗?'
            }).then(() => {
                try {
                    let orderHistory = JSON.parse(localStorage.getItem('orderHistory')) || [];
                    orderHistory = orderHistory.map(order => {
                        if (order.id === id) {
                            order.status = -1;
                        }
                        return order;
                    });
                    localStorage.setItem('orderHistory', JSON.stringify(orderHistory));
                    this.getOrderListFromLocalStorage();
                    showToast("订单已取消");
                } catch (error) {
                    console.error('取消订单失败:', error);
                    showToast("取消订单失败");
                }
            });
        },
        handleMouseEnter(index) {
            this.isHovering[index] = true;
        },
        handleMouseLeave(index) {
            this.isHovering[index] = false;
        },
        // 新增保存订单列表到本地存储的方法
        saveOrderListToLocalStorage() {
            try {
                localStorage.setItem('orderHistory', JSON.stringify(this.orderList));
            } catch (error) {
                console.error('保存订单列表到本地存储失败:', error);
            }
        }
    }
};
</script>

<style lang="less" scoped>
@bg-color: #f3f3f3;
@card-bg-color: #fff;
@primary-text-color: #333;
@secondary-text-color: #666;
@hover-bg-color: #f8f8f8;

.order-list {
    background-color: @bg-color;
    padding: 15px;
}

.card-item {
    margin: 10px;
    padding: 15px;
    background-color: @card-bg-color;
    border-radius: 10px;
    box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    font-size: 16px;
}

.card-item.card-header {
    padding: 10px;
    font-size: 16px;
    font-weight: bolder;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #e0e0e0;
}

.card-item.card-header ::v-deep.van-cell__value {
    color: @primary-text-color;
}

.product-row {
    margin-top: 10px;
}

.product-cell {
    padding: 5px 0;
}

.price-row {
    font-size: 14px;
    color: @secondary-text-color;
}

.amount {
    padding: 10px;
    text-align: right;
    color: @secondary-text-color;
    font-weight: bold;
    border-top: 1px solid #e0e0e0;
    margin-top: 10px;
}

.card-item-hover {
    background-color: @hover-bg-color;
    transform: translateY(-3px);
    box-shadow: 0 0.3rem 0.8rem rgba(0, 0, 0, 0.15);
}
</style>